package yuan.deng.utils;

import javax.sql.DataSource;
import java.io.PrintWriter;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
import java.sql.Connection;
import java.sql.SQLException;
import java.sql.SQLFeatureNotSupportedException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.logging.Logger;

public class MyDataSource implements DataSource {

    //1准备一个容器保存连接对象(线程安全的容器)
    private static List<Connection> pool = Collections.synchronizedList(new ArrayList<>());

    //2静态代码块，通过工具类获取10个连接对象
    static {
        for (int i = 0; i <10 ; i++) {
            Connection conn = JDBCUtlis.getConn();
            pool.add(conn);
        }

    }
    //3重写getConnection（） ，用于获取一个连接对象/*动态代理归还连接
    //* */
    @Override
    public Connection getConnection() throws SQLException {
        if (pool.size()>0){
            Connection conn = pool.remove(0);
            //通过自定义对象，对原有连接对象进行包装
            Connection proxy=(Connection) Proxy.newProxyInstance(conn.getClass().getClassLoader(), conn.getClass().getInterfaces(), new InvocationHandler() {
                @Override
                public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
                    if ("close".equals(method.getName())){
                        pool.add(conn);
                        return null;
                    }else {
                        return method.invoke(conn,args);
                    }
                }
            });
            proxy.close();
            MyConnection2 connection2=new MyConnection2(conn,pool);
            return conn;
        }else {
            throw new RuntimeException("连接数量已用尽");
        }
    }

    //提供一个获取连接池大小的方法
    public int getSize(){
        return pool.size();
    }
    @Override
    public Connection getConnection(String username, String password) throws SQLException {
        return null;
    }

    @Override
    public <T> T unwrap(Class<T> iface) throws SQLException {
        return null;
    }

    @Override
    public boolean isWrapperFor(Class<?> iface) throws SQLException {
        return false;
    }

    @Override
    public PrintWriter getLogWriter() throws SQLException {
        return null;
    }

    @Override
    public void setLogWriter(PrintWriter out) throws SQLException {

    }

    @Override
    public void setLoginTimeout(int seconds) throws SQLException {

    }

    @Override
    public int getLoginTimeout() throws SQLException {
        return 0;
    }

    @Override
    public Logger getParentLogger() throws SQLFeatureNotSupportedException {
        return null;
    }
}
